package com.net.xpay.common.service.impl;

import com.google.common.base.Preconditions;
import com.net.xpay.common.domain.FrozenUserLog;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.domain.UserShard;
import com.net.xpay.common.enums.user.SecurityStatus;
import com.net.xpay.common.manager.FrozenUserLogManager;
import com.net.xpay.common.manager.UserManager;
import com.net.xpay.common.manager.UserShardManager;
import com.net.xpay.core.manager.PayTransBatchManager;
import com.net.xpay.core.manager.safePay.SafePayBatchManager;
import com.net.xpay.core.model.UserSafePayTransStatModel;
import com.net.xpay.core.model.UserTransStatModel;
import com.net.xpay.common.service.UserFrozenService;
import com.net.shard.ShardUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Slf4j
@Service
public class UserFrozenServiceImpl implements UserFrozenService {

    @Autowired
    private UserManager userManager;

    @Autowired
    private UserShardManager userShardManager;

    @Autowired
    private SafePayBatchManager safePayBatchManager;

    @Autowired
    private PayTransBatchManager payTransBatchManager;

    @Autowired
    private FrozenUserLogManager frozenUserLogManager;

    @Override
    public void checkFrozenUser(Long userId) {
        Preconditions.checkArgument(userId != null);
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = LocalDateTime.now().minusDays(30L);

        User user = userManager.getById(userId);
        if (user.getSecurityStatus() == SecurityStatus.FROZEN) {
            log.warn("checkFrozenUser user already frozen userId={}", userId);
            return;
        }

        if (user.getLastLoginTime() != null && user.getLastLoginTime().isAfter(startTime)) {
            return;
        }

        if (user.getLastChargeTime() != null && user.getLastChargeTime().isAfter(startTime)) {
            return;
        }

        UserShard userShard = userShardManager.getById(userId);

        try {
            ShardUtil.setShardContext(userShard.getShardId());
            UserSafePayTransStatModel userSafePayTransStatModel = safePayBatchManager.countAmountAndTimesOfSuccess(userId, startTime, endTime);

            UserTransStatModel userTransStatModel = payTransBatchManager.countAmountAndTimesOfSuccess(userId, startTime, endTime);

            if ((userSafePayTransStatModel.getSuccessCount() + userTransStatModel.getSuccessCount() == 0L) &&
                    (new BigDecimal(userSafePayTransStatModel.getSuccessAmount()).add(new BigDecimal(userTransStatModel.getSuccessAmount()))).compareTo(new BigDecimal(0)) == 0) {
                log.info("checkFrozenUser frozen start userId={}", userId);
                FrozenUserLog frozenUserLog = new FrozenUserLog();
                frozenUserLog.setUserId(userId);
                frozenUserLog.setPartnerId(user.getPartnerId());
                frozenUserLog.setFrozenTime(LocalDateTime.now());
                String frozenReason = "30天未活跃被冻结";
                frozenUserLog.setFrozenReason(frozenReason);
                frozenUserLogManager.save(frozenUserLog);

                user = userManager.getById(userId);
                user.setSecurityStatus(SecurityStatus.FROZEN);
                user.setSecurityRemark(frozenReason);

                userManager.updateByPrimaryKeyWithVersion(user);
                log.info("checkFrozenUser frozen end userId={}", userId);
            }

        } finally {
            ShardUtil.cleanShardContext();
        }


    }
}
